package com.xuzz.study.io.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;
import java.nio.ByteBuffer;

public class TestHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject msg) throws Exception {
        if(msg instanceof HttpRequest)
        {
            System.out.println("msg的类型=="+msg.getClass());
            System.out.println("客户端的地址=="+channelHandlerContext.channel().remoteAddress());

            HttpRequest request = (HttpRequest)msg;
            URI uri = new URI(request.getUri());
            if(uri.getPath().indexOf("favicon.ico")!=-1)
            {
                System.out.println("七扭去了favicon，不做响应");
                return;
            }
            //回复信息给浏览器
            ByteBuf content= Unpooled.copiedBuffer("hallo", CharsetUtil.UTF_8);
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    content
            );
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());

            channelHandlerContext.writeAndFlush(response);
        }
    }
}
